const $ = layui.jquery;
let form=layui.form;
let layer=layui.layer;
let upload=layui.upload;
$(() => {
    //     渲染图片上传
    upload.render({
        elem: '#avatar-upload-btn',
        url: ctx + '/sys/api/v1/upload/image',
        data: {//传的数据,这个type是自己起的名字，在后面会用到
            type: "admin_avatar",
        },
        exts: 'jpg|png|gif|bmp|jpeg|svg', //上传的类型
        size: 1024,
        done: function (resp) {//上传完成，响应200状态码进入
            let url = ctx + "/assets/" + resp.data;
            $(".avatar-preview").css("background-image", "url(" + url + ")");
            sessionStorage.setItem("admin_avatar", resp.data);//将图片地址存到会话存储域
        },
        error: function () {
            layer.msg("上传图片失败");
        },

    });
//     自定义验证规则,key为表单元素的name
    form.verify({
        username: function (value, elem) {
            if (value.length < 3 || value.length > 20) {
                return "管理名长度必须介于3~20位之间";
            }
        }
    })
    $('#register_btn').click(function () {
        let pass=form.validate("#add-form")//参数验证
        if(!pass){
            return;
        }
        // 验证通过，向后台发请求
        const url=ctx+"/sys/api/v1/admin";
        let formData = form.val("add-form");//参数为过滤器
        let avatarUrl=sessionStorage.getItem("admin_avatar");
        if(avatarUrl){
            formData.avatarUrl=avatarUrl;
        }
        $.ajax({
            url,
            method:"post",
            data: formData,
            success(resp){
                if(resp.success){
                   layer.msg('注册成功，现为您跳转至登录页登录',{icon:1},function (){
                       location.href="/vm/sys/login"
                   })
                }
            },error(resp){
                let json = resp.responseJSON;
                let msg=json.msg||"注册管理员异常";
                layer.msg(msg);
            }
        })

    })

})